package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    DishMapper dishMapper;

    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        // 1.判断当前商品是否已经添加到购物车中
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());



       List<ShoppingCart> list =  shoppingCartMapper.list(shoppingCart);


       // 如果存在，这数量加1
       if(list!=null && list.size()>0){
           ShoppingCart shoppingCart1 = list.get(0);
           shoppingCart.setNumber(shoppingCart1.getNumber()+1);
           shoppingCartMapper.updateById(shoppingCart1);
       }else{
           // 如果不存在，添加到购物车，数量默认为1，并根据是套餐还是商品分别添加
           if(shoppingCartDTO.getSetmealId()!=null){
               // 构造套餐需要的 ShoppingCart
               Setmeal setmealDish = setmealMapper.getById(shoppingCartDTO.getSetmealId());
               shoppingCart.setName(setmealDish.getName());
               shoppingCart.setImage(setmealDish.getImage());
               shoppingCart.setAmount(setmealDish.getPrice());
           }else{
               // 构造商品需要的 shoppingCart
               Dish dish = dishMapper.getDishById(shoppingCart.getDishId());
               shoppingCart.setName(dish.getName());
               shoppingCart.setImage(dish.getImage());
               shoppingCart.setAmount(dish.getPrice());
           }
           shoppingCart.setNumber(1);
           shoppingCart.setCreateTime(LocalDateTime.now());

           // 构造完毕后，新增数据

           shoppingCartMapper.insert(shoppingCart);


       }





    }

    @Override
    public List<ShoppingCart> list() {
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        return list;
    }

    @Override
    public void deleteAll() {
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        shoppingCartMapper.deleteAll(shoppingCart);

    }
}
